package com.xuetang9.t9.hotel.mapper.sql.impl;

import com.xuetang9.t9.hotel.mapper.condition.ICondition;
import com.xuetang9.t9.hotel.mapper.condition.impl.GuestCondition;
import com.xuetang9.t9.hotel.mapper.sql.IMapperSql;
import org.apache.ibatis.jdbc.SQL;

import java.util.Map;

/**
 * @author Pang
 */
public class GuestMapperSql implements IMapperSql {

    @Override
    public String selectByAll(Map map){
        ICondition key = (ICondition) map.get("key");
        return getSql("*",key,true);
    }

    @Override
    public String selectByCount(Map map){
        ICondition key = (ICondition) map.get("key");
        return getSql("COUNT(*)",key,false);
    }

    private String getSql(String head,ICondition condition,boolean isPage){
        SQL sql = new SQL();
        sql.SELECT(head).FROM("g_guest");
        if(condition == null){
            return sql.toString();
        }
        GuestCondition key = null;
        if(condition instanceof GuestCondition){
            key = (GuestCondition)condition;
        }else{
            throw  new RuntimeException("condition type Don't match");
        }
        if(null == key) {return sql.toString();};
        if(null != key.getName() && !key.getName().isEmpty()){
            sql.WHERE("guest_name LIKE '%"+key.getName()+"%'");
        }
        if(null != key.getNum() && !key.getNum().isEmpty()){
            sql.WHERE("card_num LIKE '%"+key.getNum()+"%'");
        }
        if(null != key.getPhone() && !key.getPhone().isEmpty()){
            sql.WHERE("guest_phone LIKE '%"+key.getPhone()+"%'");
        }
        if(null != key.getState() && key.getState() >= 0){
            sql.WHERE("guest_state = "+key.getState());
        }
        if(key.judge()  && isPage){
            sql.LIMIT(key.getCurrPage()+","+key.getPageSize());
        }
        return sql.toString();
    }

}
